// pages/my/invitecode/invitecode.js
Page({
  data: {
    count: 0,
    imgLink: "",
    canvas_obj: "",
    canvasIMG: "",
    is_canvas: true
  },
  onLoad(options) {
    getApp().globalData.http.inviteCode().then(res => {
      this.setData({
        imgLink: res.data.image,
        count: res.data.count
      });
    });
  },
  onShareAppMessage() {},
  draw(callback) {
    const systemInfo = wx.getSystemInfoSync();

    function topx(val) {
      return val / 750 * systemInfo.windowWidth
    }

    const query = wx.createSelectorQuery()
    query.select("#canvas")
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node
        this.setData({
          canvas_obj: canvas
        })
        const ctx = canvas.getContext('2d')
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr)

        let bg = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
        bg.addColorStop(0, "#62DDA1");
        bg.addColorStop(1, "#33B868");
        ctx.fillStyle = bg;
        ctx.rect(0, 0, canvas.width, canvas.height)
        ctx.fill()

        let logo = canvas.createImage();
        logo.src = "https://www.linxiaobang.com.cn/miniprogram/image/logo_text@2x.png";
        logo.onload = () => ctx.drawImage(logo, topx(32), topx(24), topx(104), topx(50));

        ctx.font = `bold ${topx(24)}px sans-serif`;
        ctx.fillStyle = "#1E6B3D";
        ctx.fillText("郑州人的社区服务平台，你来也看看吧~", topx(32), topx(110));

        let card = canvas.createImage();
        card.src = "https://www.linxiaobang.com.cn/miniprogram/image/invite_card_bg@2x.png";
        card.onload = () => {
          ctx.drawImage(card, topx(24), topx(140), topx(552), topx(842));

          ctx.font = `bold ${topx(22)}px PingFangSC-Medium`;
          ctx.fillStyle = "#303135";
          ctx.fillText("邀请好友，升级VIP，享受更多平台特权～", topx(92), topx(192));

          let code = canvas.createImage();
          code.src = this.data.imgLink;
          code.onload = () => {
            ctx.drawImage(code, topx(52), topx(280), topx(488), topx(488));

            callback && callback();
          };
        };

      });
  },
  save() {
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting["scope.writePhotosAlbum"]) {
          getApp().globalData.vant.dialog.confirm({
            title: "温馨提示",
            message: "打开保存相册权限，才能保存哦~",
            showCancelButton: false,
            confirmButtonText: "去授权",
            confirmButtonOpenType: "openSetting",
            confirmButtonColor: "#33B868"
          }).then(() => {});
        } else {
          this.setData({
            is_canvas: false
          }, () => {
            this.draw(() => {
              this.download();
            });
          });
        }
      }
    });
  },
  download() {
    let _this = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      canvas: this.data.canvas_obj,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: res => {
            getApp().globalData.vant.toast({
              type: "success",
              message: "保存成功",
              duration: 1000,
            });
          },
          fail: e => {
            console.log(e)
          },
          complete: () => {
            _this.setData({
              is_canvas: true
            });
          }
        });
      },
      fail(err) {
        console.log(err)
      }
    }, this);
  },
  share() {
    let _this = this;
    _this.setData({
      is_canvas: false
    }, () => {
      _this.draw(() => {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          canvas: _this.data.canvas_obj,
          success: function (res) {
            wx.showShareImageMenu({
              path: res.tempFilePath,
              complete: () => {
                _this.setData({
                  is_canvas: true
                });
              }
            });
          },
          fail(err) {
            console.log(err)
          }
        }, this);
      });
    });
  }
})